using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace Lzfy_His_Service.Controllers
{
    /// <summary>
    /// 企业微信消息推送控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class WeChatMessageController : ControllerBase
    {
        private readonly IWeChatWorkService _weChatWorkService;
        private readonly ILogger<WeChatMessageController> _logger;

        public WeChatMessageController(
            IWeChatWorkService weChatWorkService,
            ILogger<WeChatMessageController> logger)
        {
            _weChatWorkService = weChatWorkService;
            _logger = logger;
        }

        /// <summary>
        /// 发送企业微信消息
        /// </summary>
        /// <param name="request">消息推送请求</param>
        /// <returns>消息推送响应</returns>
        [HttpPost("send")]
        public async Task<ActionResult<ApiResponse<WeChatWorkMessageResponse>>> SendMessage([FromBody] WeChatWorkMessageRequest request)
        {
            try
            {
                _logger.LogInformation("接收到企业微信消息推送请求，用户ID: {UserId}, 消息类型: {MessageType}", request.UserId, request.MessageType);

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                    return BadRequest(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = false,
                        Message = string.Join("; ", errors)
                    });
                }

                var result = await _weChatWorkService.SendMessageAsync(request);
                
                if (result.Success)
                {
                    _logger.LogInformation("企业微信消息发送成功，用户ID: {UserId}, 消息ID: {MessageId}", request.UserId, result.MessageId);
                    return Ok(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = true,
                        Data = result,
                        Message = "消息发送成功"
                    });
                }
                else
                {
                    _logger.LogWarning("企业微信消息发送失败，用户ID: {UserId}, 错误: {Error}", request.UserId, result.Message);
                    return BadRequest(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = false,
                        Data = result,
                        Message = result.Message
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送企业微信消息异常，用户ID: {UserId}", request.UserId);
                return StatusCode(500, new ApiResponse<WeChatWorkMessageResponse>
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 发送文本消息
        /// </summary>
        /// <param name="request">文本消息请求</param>
        /// <returns>消息推送响应</returns>
        [HttpPost("send-text")]
        public async Task<ActionResult<ApiResponse<WeChatWorkMessageResponse>>> SendTextMessage([FromBody] SendTextMessageRequest request)
        {
            try
            {
                _logger.LogInformation("接收到发送文本消息请求，用户ID: {UserId}", request.UserId);

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                    return BadRequest(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = false,
                        Message = string.Join("; ", errors)
                    });
                }

                var result = await _weChatWorkService.SendTextMessageAsync(request.UserId, request.Content);
                
                if (result.Success)
                {
                    _logger.LogInformation("文本消息发送成功，用户ID: {UserId}, 消息ID: {MessageId}", request.UserId, result.MessageId);
                    return Ok(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = true,
                        Data = result,
                        Message = "文本消息发送成功"
                    });
                }
                else
                {
                    _logger.LogWarning("文本消息发送失败，用户ID: {UserId}, 错误: {Error}", request.UserId, result.Message);
                    return BadRequest(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = false,
                        Data = result,
                        Message = result.Message
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送文本消息异常，用户ID: {UserId}", request.UserId);
                return StatusCode(500, new ApiResponse<WeChatWorkMessageResponse>
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 发送文本卡片消息
        /// </summary>
        /// <param name="request">文本卡片消息请求</param>
        /// <returns>消息推送响应</returns>
        [HttpPost("send-textcard")]
        public async Task<ActionResult<ApiResponse<WeChatWorkMessageResponse>>> SendTextCardMessage([FromBody] SendTextCardMessageRequest request)
        {
            try
            {
                _logger.LogInformation("接收到发送文本卡片消息请求，用户ID: {UserId}, 标题: {Title}", request.UserId, request.Title);

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                    return BadRequest(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = false,
                        Message = string.Join("; ", errors)
                    });
                }

                var result = await _weChatWorkService.SendTextCardMessageAsync(
                    request.UserId, 
                    request.Title, 
                    request.Description, 
                    request.Url, 
                    request.BtnTxt);
                
                if (result.Success)
                {
                    _logger.LogInformation("文本卡片消息发送成功，用户ID: {UserId}, 消息ID: {MessageId}", request.UserId, result.MessageId);
                    return Ok(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = true,
                        Data = result,
                        Message = "文本卡片消息发送成功"
                    });
                }
                else
                {
                    _logger.LogWarning("文本卡片消息发送失败，用户ID: {UserId}, 错误: {Error}", request.UserId, result.Message);
                    return BadRequest(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = false,
                        Data = result,
                        Message = result.Message
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送文本卡片消息异常，用户ID: {UserId}", request.UserId);
                return StatusCode(500, new ApiResponse<WeChatWorkMessageResponse>
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 发送Markdown消息
        /// </summary>
        /// <param name="request">Markdown消息请求</param>
        /// <returns>消息推送响应</returns>
        [HttpPost("send-markdown")]
        public async Task<ActionResult<ApiResponse<WeChatWorkMessageResponse>>> SendMarkdownMessage([FromBody] SendMarkdownMessageRequest request)
        {
            try
            {
                _logger.LogInformation("接收到发送Markdown消息请求，用户ID: {UserId}", request.UserId);

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                    return BadRequest(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = false,
                        Message = string.Join("; ", errors)
                    });
                }

                var result = await _weChatWorkService.SendMarkdownMessageAsync(request.UserId, request.Content);
                
                if (result.Success)
                {
                    _logger.LogInformation("Markdown消息发送成功，用户ID: {UserId}, 消息ID: {MessageId}", request.UserId, result.MessageId);
                    return Ok(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = true,
                        Data = result,
                        Message = "Markdown消息发送成功"
                    });
                }
                else
                {
                    _logger.LogWarning("Markdown消息发送失败，用户ID: {UserId}, 错误: {Error}", request.UserId, result.Message);
                    return BadRequest(new ApiResponse<WeChatWorkMessageResponse>
                    {
                        Success = false,
                        Data = result,
                        Message = result.Message
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送Markdown消息异常，用户ID: {UserId}", request.UserId);
                return StatusCode(500, new ApiResponse<WeChatWorkMessageResponse>
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }
    }

    /// <summary>
    /// 发送文本消息请求
    /// </summary>
    public class SendTextMessageRequest
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        [Required(ErrorMessage = "用户ID不能为空")]
        public string UserId { get; set; } = string.Empty;

        /// <summary>
        /// 消息内容
        /// </summary>
        [Required(ErrorMessage = "消息内容不能为空")]
        public string Content { get; set; } = string.Empty;
    }

    /// <summary>
    /// 发送文本卡片消息请求
    /// </summary>
    public class SendTextCardMessageRequest
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        [Required(ErrorMessage = "用户ID不能为空")]
        public string UserId { get; set; } = string.Empty;

        /// <summary>
        /// 标题
        /// </summary>
        [Required(ErrorMessage = "标题不能为空")]
        public string Title { get; set; } = string.Empty;

        /// <summary>
        /// 描述
        /// </summary>
        [Required(ErrorMessage = "描述不能为空")]
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 跳转链接
        /// </summary>
        public string Url { get; set; } = string.Empty;

        /// <summary>
        /// 按钮文字
        /// </summary>
        public string BtnTxt { get; set; } = "详情";
    }

    /// <summary>
    /// 发送Markdown消息请求
    /// </summary>
    public class SendMarkdownMessageRequest
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        [Required(ErrorMessage = "用户ID不能为空")]
        public string UserId { get; set; } = string.Empty;

        /// <summary>
        /// Markdown内容
        /// </summary>
        [Required(ErrorMessage = "Markdown内容不能为空")]
        public string Content { get; set; } = string.Empty;
    }
}
